<template>
    <div class="header" style="display: flex; justify-content: flex-end; padding: 10px 0;">
      <el-button type="warning"  @click="addNavDialogRef.show = true">添加导航</el-button>
    </div>

    <el-tabs v-model="choosedNav" type="border-card" class="tab-list" @tab-change="handleTabChange">
        <template v-for="nav in navList" :key="nav">
          <el-tab-pane :label="nav" :name="nav" style="height: 100%; display: flex; flex-direction: row;">
            <el-tree
              style="width: 50%; height: 100%; overflow: auto;"
              :data="dataTree"
              :props="defaultProps"
              node-key="id"
              :current-node-key="choosedID"
              :highlight-current="true"
              @node-contextmenu="handleNodeRightClick">

              <template #default="{ node, data }">
                <span style="display: flex; align-items: start; ">
                  <img v-if="data.children " src="../assets/img/Dir.svg" style="width: 20px; height: 20px; margin-right: 2px; vertical-align: middle;">
                  <img v-else src="../assets/img/File.svg" style="width: 18px; height: 18px; margin-right: 2px;  vertical-align: middle;">
                  <span>{{ data.label}}</span>
                </span>
              </template>
          </el-tree>
          <div style="width: 50%; height: 100%; overflow: auto; margin: 10px 10px;"  >
            <el-button type="primary" @click="addTopDirDialogRef.show = true">新增一级目录</el-button>
          </div>
        </el-tab-pane>
      </template>  
    </el-tabs>

  <!-- 弹窗输入框 -->
  <InputDialog 
          title="增加导航" 
          ref="addNavDialogRef"
          @submitInput="addNav">
  </InputDialog>

  <!-- 写文章 -->
  <InputDialog 
          title="写文章-输入名称" 
          ref="writeNoteDialogRef"
          @submitInput="writeNote">
  </InputDialog>

  <!-- 新建目录 -->
  <InputDialog 
          title="新建目录" 
          ref="addDirDialogRef"
          @submitInput="addDir">
  </InputDialog>

  <!-- 新建top目录 -->
  <InputDialog 
          title="新建一级目录" 
          ref="addTopDirDialogRef"
          @submitInput="addTopDir">
  </InputDialog>
  
  <!-- 重命名 -->
  <InputDialog 
          title="重命名" 
          ref="renameDialogRef"
          @submitInput="renameNode">
  </InputDialog>

  
  <!-- ------------------------------------------右键菜单 -------------------------------------------------------------->
  <!-- 遮罩层 -->
  <div v-if="contextMenuVisible" class="overlay" @click="contextMenuVisible = false;" @contextmenu="contextMenuVisible = false;"></div>
  <div
      class="context-menu"
      v-if="contextMenuVisible"
      :style="{ position: 'absolute', top: contextMenuPosition.y + 'px', left: contextMenuPosition.x + 'px'}"
      @contextmenu.prevent
    >
      <ul>
        <!-- 写文章 -->
        <li v-if="rightMenu.writeNote.enable" @click="()=>{contextMenuVisible=false; writeNoteDialogRef.show=true}">{{ rightMenu.writeNote.text }}</li>
        <!-- markdown编辑-->
        <li v-if="rightMenu.editMarkdown.enable" @click="onEditMarkdownClicked">{{ rightMenu.editMarkdown.text }}</li>
        <!-- 新增目录 -->
        <li v-if="rightMenu.addDir.enable"  @click="()=>{contextMenuVisible=false;addDirDialogRef.show=true}">{{ rightMenu.addDir.text }}</li>
        <!-- 重命名 -->
        <li v-if="rightMenu.rename.enable" @click="()=>{contextMenuVisible=false;
                renameDialogRef.show=true; 
                renameDialogRef.inputValue = choosedNode.label.endsWith('.md')
                  ? choosedNode.label.slice(0, -3) 
                  : choosedNode.label; }">
            {{ rightMenu.rename.text }}
        </li>
        <!-- 移动 -->
        <li v-if="rightMenu.move.enable" @click="()=>{contextMenuVisible=false; moveDialogVisible = true}">{{ rightMenu.move.text }}</li>
        <!-- 删除 -->
        <li v-if="rightMenu.delete.enable" @click="()=>{contextMenuVisible=false;deleteNode()}">{{ rightMenu.delete.text }}</li>
        <!-- 编辑readMe -->
        <li v-if="rightMenu.readMe.enable" @click="()=>{contextMenuVisible=false; onEditMarkdownClicked()}">{{ rightMenu.readMe.text }}</li>
      </ul>
  </div>
  

<!-- 移动el-tree -->
<MoveDialog v-if="moveDialogVisible" :nodeID="choosedID" 
          :level="choosedNode.level" 
          @close="moveDialogVisible=false" 
          @submit="handleMovedDialogSubmit"
          >
</MoveDialog>

</template>

<script setup>

import { ref } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { sortDirFunction } from '@/assets/js/dirSort'
import InputDialog  from '../components/InputDialog.vue'
import {useConfigStore} from "../stores/config";
import MoveDialog from '../components/MoveDialog.vue';


const configStore = useConfigStore();

const choosedNav = ref('')  // 当前选中的tab
const navList = ref([]);  // 导航列表
const choosedNode = ref({});  // 当前选中的节点
const choosedID = ref(null);  // 当前选中的节点id
const dataTree = ref([]);  // 目录树的数据

let loadingInstance; // loading实例


// =====================顶部添加导航按钮================================
const addNavDialogRef = ref(null);

const addNav = async (newNavName) => {
  
  if (newNavName.trim()) {
    const res = await window.api.createDir("/" + newNavName);
    if (!res.success) {
      ElMessage.error({ message: res.msg });
    } else {
      await loadNavList();
      choosedNav.value = newNavName.trim(); // 设置当前选中的 tab 为新增的 tab
      addNavDialogRef.value.show = false;
      dataTree.value = await window.api.getPostsTree(choosedNav.value);  // 更新获取目录树
    }
  }else{
    ElMessage.error({ message: '请输入导航名称' });
  }
  
};

// 写入配置文件
const write2VitepressConfig = async ()=>{
  const res = await window.api.generateVitepressConfig();
  if (!res.success) {
    ElMessage.error({ message: "出现错误，请检查配置文件" });
  } else {
    ElMessage.success({ message: "配置文件写入成功", duration: 1000});
  }
}



// 加载导航
const loadNavList = async() => {
  let res = await window.api.getNavList()
  navList.value = sortDirFunction.sortDir(res)
  choosedNav.value = navList.value[0] || '' // 默认选中第一个tab
  handleTabChange(navList.value[0])
}
loadNavList();




// =====================下方目录树================================
const defaultProps = {
  children: 'children',
  label: 'label',
}


// 导航切换事件
const handleTabChange = async (nav) => {
  choosedNav.value = nav
  const res = await window.api.getPostsTree(nav)
  dataTree.value = res

  choosedID.value = dataTree.value.length > 0 ? dataTree.value[0].id : ""
}


// =====================右键菜单================================


const rightMenu = ref({
  writeNote: { text: "写笔记", enable: true },
  editMarkdown: { text: "typora-编辑", enable: true },
  addDir: { text: "新增目录", enable: true },
  rename: { text: "重命名", enable: true },
  move: { text: "移动", enable: true },
  delete: { text: "删除", enable: true },
  readMe: { text: "编辑ReadMe", enable: true },
})


const contextMenuVisible = ref(false);  // 右键菜单是否显示
const contextMenuPosition = ref({ x: 0, y: 0 });  // 右键菜单位置

// 右键etree事件
const handleNodeRightClick = (event, data, node, t) => {
  event.preventDefault();
  contextMenuPosition.value.x = event.clientX;
  contextMenuPosition.value.y = event.clientY;
  // 有孩子是目录
  if (node.data.children) {
    rightMenu.value.writeNote.enable = true
    rightMenu.value.editMarkdown.enable = false
    rightMenu.value.addDir.enable = true
    rightMenu.value.rename.enable = true
    rightMenu.value.delete.enable = true
    if (node.level == 1) {
      rightMenu.value.readMe.enable = true
    }else{
      rightMenu.value.readMe.enable = false
    }
    
  }else{
    rightMenu.value.writeNote.enable = false
    rightMenu.value.editMarkdown.enable = true
    rightMenu.value.addDir.enable = false
    rightMenu.value.rename.enable = true
    rightMenu.value.delete.enable = true
    rightMenu.value.readMe.enable = false
  }

  choosedNode.value = node;  // 右键选中的节点
  choosedID.value = node.data.id;  // 右键选中的节点id
  contextMenuVisible.value = true;  // 右键菜单显示
};



// 右键写文章, 写文章是新建文章
const writeNoteDialogRef = ref(null);
const writeNote = async (fileName) => {
    const newPostId = choosedID.value + "/" + fileName + ".md"
    const res = await window.api.writeNewNote(newPostId, "")
    
    if (res.success){
      window.api.openTypora(newPostId)
      dataTree.value = await window.api.getPostsTree(choosedNav.value);  // 更新获取目录树
      choosedID.value = newPostId
      writeNoteDialogRef.value.show = false;  // 关闭对话框
      write2VitepressConfig()  // 更新vitepress配置文件
      loadingInstance = ElLoading.service({
      text: '正在编辑中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
      
    }else{
      ElMessage.error({ message: res.msg });
    }
}

// 右键删除
const deleteNode = async () => {
  if(!choosedNode.value.isLeaf && configStore.runningFlag){
      ElMessage.error({ message: '请先停止服务' });
      return
  }
  const comfimation = await ElMessageBox.confirm('确定删除该节点吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })

  if(comfimation){
    const res = await window.api.deleteNode(choosedID.value)
    if (res.success){
      dataTree.value = await window.api.getPostsTree(choosedNav.value);  // 更新获取目录树
      choosedID.value = ""   // 更新当前节点指针
      write2VitepressConfig()  // 更新vitepress配置文件
    }else{
      ElMessage.error({ message: res.msg });
    }
  } 
}


// 右键重命名
const renameDialogRef = ref(null);
const renameNode = async (newName) => {
  if (choosedNode.value == null ) {
        ElMessage.error({ message: '出现错误' });
        return
  }
  if(!choosedNode.value.isLeaf && configStore.runningFlag){
      ElMessage.error({ message: '请先停止服务' });
      return
  }

  let new_choosedID = null
  if (newName.trim()) {
      try{
        new_choosedID = choosedNode.value.isLeaf 
            ? choosedID.value.replace(/\/([^\/]+)$/,"/" + newName.trim() + ".md")
            : choosedID.value.replace(/\/([^\/]+)$/,"/" + newName.trim())
        const res = await window.api.renameFile(choosedID.value, new_choosedID);  // 重命名
        if (res && res.success){
          dataTree.value = await window.api.getPostsTree(choosedNav.value);  // 更新获取目录树
          renameDialogRef.value.show = false;  // 关闭对话框
          choosedID.value = new_choosedID;  // 更新当前节点指针
          write2VitepressConfig()  // 更新vitepress配置文件
        }else{
          ElMessage.error({ message: res.msg || '出现未知错误2' });
        }
      } catch (error) {
          ElMessage.error({ message: error.message || '出现未知错误' });
      }
    }
}

// 右键新增目录
const addDirDialogRef = ref(null);
const addDir = async (newName) => {
  let new_choosedID = choosedID.value + "/" + newName
  const res = await window.api.createDir(new_choosedID)
  if (res.success){
    dataTree.value = await window.api.getPostsTree(choosedNav.value);  // 更新获取目录树
    addDirDialogRef.value.show = false;  // 关闭对话框
    choosedID.value = new_choosedID  // 更新当前节点
    write2VitepressConfig()  // 更新vitepress配置文件
  }else{
    ElMessage.error({ message: res.msg });
  }
}

// 右键移动
const moveDialogVisible = ref(false)

const handleMovedDialogSubmit = async (res) => {
  moveDialogVisible.value = false
  if (res.success){
    dataTree.value = await window.api.getPostsTree(choosedNav.value);  // 更新获取目录树
    choosedID.value = null
    write2VitepressConfig()  // 更新vitepress配置文件
    ElMessage.success({ message: res.msg });
  }else{
    ElMessage.error({ message: res.msg });
  }


}


// 新增Top目录
const addTopDirDialogRef = ref(null);
const addTopDir = async (newName) => {
  if (newName.trim() == ''){
    return
  }
  const noteId = choosedNav.value + "/" + newName
  const res = await window.api.createDir(noteId)
  if (res.success){
    await window.api.writeNewNote(noteId + "/" + "index.md", "### " + newName)
    dataTree.value = await window.api.getPostsTree(choosedNav.value);  // 更新获取目录树
    addTopDirDialogRef.value.show = false;  // 关闭对话框
    choosedID.value = noteId  // 更新当前节点
    write2VitepressConfig()  // 更新vitepress配置文件
  }else{
    ElMessage.error({ message: res.msg });
  }
}


// --------------------------------------------------markdown-------------------------------------------

const onEditMarkdownClicked = async () => {
  contextMenuVisible.value=false  // 隐藏右键菜单

  if (choosedID.value.endsWith(".md")) {
     window.api.openTypora(choosedID.value)
  }else{
     window.api.openTypora(choosedID.value + "/index.md")
  }
  // 等待加载
  loadingInstance = ElLoading.service({
    text: '正在编辑中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
}



window.api.onExitTypora((event, res)=>{
  if (!res.success){
    ElMessage.error({ message: res.msg || '出现未知错误' });
  }
  if (loadingInstance) {
      
      loadingInstance.close();
  }
  
})
</script>

<style lang="scss" scoped>



.tab-list {
  background-color: inherit;
  padding-bottom: 0;
  height: calc(100vh - 75px);
  :deep(.el-tabs__header) {
    background-color: inherit;
    
  }
  :deep(.el-tabs__nav-wrap){
    padding: 0 40px;
  }

  :deep(.el-tabs__nav-prev){
    font-size: 16px;
    padding: 0 10px;
  }
  :deep(.el-tabs__nav-next){
    font-size: 16px;
    padding: 0 10px;
  }
  :deep(.el-tabs__item){
    font-size: 16px;
    font-weight: bold;
    color: #dbc928;
  }
  :deep(.el-tabs__item:hover){
    color: #c8b82b !important;
  }
  :deep(.el-tabs__item.is-active){
    background-color: rgba(0, 0, 0, 0.4);
    color: #dbc928;
  }
  :deep(.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content){
    background-color: rgba(0, 0, 0, 0.3);
  }
}


.el-tree{
  background: transparent;
  color: white;
  font-weight: 400;
  --el-tree-node-hover-bg-color: rgba(0, 0, 0, 0.2);
  border-right: 2px solid rgba(255, 255, 255, 0.2);
}

// el-tree换行
:deep(.el-tree-node) {
      white-space: normal;
      .el-tree-node__content {
        align-items: start;
        height: 100%;
    }
}


// 右键菜单
.context-menu{
  z-index: 9999;
  background-color: #131414;
  border-radius: 5px;
  border-width: 2px;
  border-color: #2c2b2b;
  border-style: solid;
  ul{
    list-style-type: none;
    padding-left: 15px;
   li{
    padding:5px 15px;
    cursor: pointer;
   }
   li:hover{
    color: #c8c8c8;
   }
  }
}

/* 遮罩层 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 1000;
  cursor: not-allowed;
}


.fullscreen {
  width: 100% !important;  /* 使右侧编辑器占据整个区域 */
  height: 100vh;  /* 高度占满屏幕 */
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background-color: white;
  z-index: 100;
}
</style>